package service

import (
	"errors"
	"gorm.io/gorm"
	"tdy-backend/app/core/service"
	"tdy-backend/app/panoramic/dto"
	"tdy-backend/app/panoramic/model"
)

type SceneService struct {
	service.BaseService
}

//加入场景至作品
func (o *SceneService) JoinTo(param *dto.SceneJoinDto) error {
	db := o.DB

	materialService := MaterialService{}
	materialService.MakeORM(db)
	materialsInfo, err := materialService.GetMaterialMoreRow(param.MaterialIds)
	if err != nil {
		return err
	}
	scenes := []model.Scene{}
	for _, material := range *materialsInfo {
		sceneInfo := &model.SceneInfo{}
		if material.Info != nil {
			sceneInfo.TileSize = material.Info.TileSize
			sceneInfo.Levels = material.Info.Levels
			sceneInfo.Resolution = material.Info.Resolution
		}
		scenes = append(scenes, model.Scene{
			Title:      material.Title,
			WorksId:    param.WorksId,
			MemberId:   o.MemberInfo.ID,
			MaterialId: material.ID,
			GroupId:    param.GroupId,
			Kind:       material.Kind,
			Path:       material.Path,
			Info:       sceneInfo,
			Lat:        material.Lat,
			Lng:        material.Lng,
			Alt:        material.Alt,
		})
	}
	create := db.Create(&scenes)
	if create.Error != nil {
		return create.Error
	}

	return nil
}

func (o *SceneService) Delete(param *dto.SceneDeleteDto) error {

	scenes := []model.Scene{}
	db := o.DB
	scenesInfo := db.Where("id IN ?", param.Ids).Where("member_id=?", o.MemberInfo.ID).Find(&scenes)
	if scenesInfo.RowsAffected == 0 {
		return errors.New("场景数据不存在")
	}

	db.Delete(&scenes)
	return nil

}

func (o *SceneService) Edit() {

}

func (o *SceneService) ListAll(param *dto.SceneListDto) *[]model.Scene {
	scenes := []model.Scene{}
	db := o.DB

	db.Where("works_id=?", param.WorksId).
		Where("member_id=?", o.MemberInfo.ID).
		Order("id asc").
		Find(&scenes)

	return &scenes
}

func (o *SceneService) GetSceneOneRow(sceneId uint) (*model.Scene, error) {

	scene := model.Scene{}
	db := o.DB
	sceneInfo := db.Where("id=?", sceneId).Where("member_id=?", o.MemberInfo.ID).First(&scene)
	if errors.Is(sceneInfo.Error, gorm.ErrRecordNotFound) {
		return nil, errors.New("作品数据不存在")
	}
	return &scene, nil

}
